package peer.player2;


public class AutoSeekKeyThread implements Runnable{
	Thread mainThread;
	Player player;
	boolean seekForward;
	boolean isStart=false;
	int seekInteval;
	public AutoSeekKeyThread(){
		
	}
	
	void startSeek(boolean seekForward,int seekInteval){
		Player.unLock();
		this.seekInteval=seekInteval;
		this.seekForward=seekForward;
		mainThread=new Thread(this);
		mainThread.start();
	}
	public void run(){
		isStart=true;
		int tt=Player.playOffset;
		  if(seekForward){
			  tt+=seekInteval;
			  Player.seekto(tt);
			  try {
				Thread.sleep(500);
			} catch (InterruptedException e1) {
				isStart=false;
				return;
			}
			  while(true){
				  if((tt-Player.playOffset)<seekInteval){
					  tt+=seekInteval;
					  if(tt>Player.playOffset){
						  Player.seekto(tt);
					  }
				  }
				  try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					break;
				}
			}
			  isStart=false;
		  }else{
			  int sum=0;
			  Player.seekInt(-seekInteval);
			  sum+=seekInteval;
			  try {
				Thread.sleep(500);
			} catch (InterruptedException e1) {
				isStart=false;
				return;
			}
			int lastOffset=0;
			int dir=Player.playOffset-seekInteval;
			while(true){
				  if(Player.playOffset-lastOffset>0){
					  Player.seekInt(-seekInteval*3);
					}
				  if(Player.playOffset-dir<3*seekInteval){
					  Player.seekto(dir);
					  dir-=seekInteval;
					  lastOffset=Player.playOffset;
				  }
				  lastOffset=Player.playOffset;
				  try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					break;
				}
			}
			  isStart=false;
		  }
	}
	
	void stopSeek(){
		if(mainThread!=null){
			mainThread.interrupt();
		}
		
	}
}
